package com.tea.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tea.Model.Cart;
import com.tea.Model.Goods;
import com.tea.Model.GoodsSpec;
import com.tea.Model.dto.CartAddDTO;
import com.tea.Model.dto.CartUpdateDTO;
import com.tea.Model.vo.CartVO;
import com.tea.mapper.CartMapper;
import com.tea.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartService extends ServiceImpl<CartMapper, Cart> {

    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsSpecService goodsSpecService;

    // 核心添加购物车逻辑
    @Transactional
    public void addToCart(CartAddDTO dto) {
        // 获取当前用户的openid
        String userOpenid = SecurityUtils.getUserOpenid();

        // 验证商品和规格是否存在
        Goods goods = goodsService.getById(dto.getGoodsId());
        GoodsSpec spec = goodsSpecService.getById(dto.getSpecId());
        
        if (goods == null || !goods.getStatus().equals("1")) {
            throw new RuntimeException("商品不存在或未上架");
        }
        if (spec == null || !spec.getGoodsId().equals(goods.getId())) {
            throw new RuntimeException("规格信息错误");
        }
        
        // 检查规格库存
        if (spec.getStockNum() == null || spec.getStockNum() < dto.getQuantity()) {
            throw new RuntimeException("规格库存不足");
        }
        
        // 查询是否已存在购物车项（使用openid作为用户标识）
        QueryWrapper<Cart> wrapper = new QueryWrapper<Cart>()
                .eq("user_id", userOpenid)
                .eq("goods_id", dto.getGoodsId())
                .eq("spec_id", dto.getSpecId());
        
        Cart existing = this.getOne(wrapper);
        
        if (existing != null) {
            // 合并数量
            existing.setQuantity(existing.getQuantity() + dto.getQuantity());
            this.updateById(existing);
        } else {
            // 新增记录（使用openid作为user_id）
            Cart cart = new Cart();
            cart.setUserId(userOpenid);
            cart.setGoodsId(dto.getGoodsId());
            cart.setSpecId(dto.getSpecId());
            cart.setQuantity(dto.getQuantity());
            cart.setCreateTime(LocalDateTime.now());
            this.save(cart);
        }
    }

    // 获取购物车列表（带商品详情）
    public List<CartVO> getCartList() {
        // 获取当前用户的openid
        String userOpenid = SecurityUtils.getUserOpenid();
        return baseMapper.selectCartDetails(userOpenid);
    }

    // 更新数量
    @Transactional
    public void updateQuantity(CartUpdateDTO dto) {
        // 获取当前用户的openid
        String userOpenid = SecurityUtils.getUserOpenid();
        
        Cart cart = this.getById(dto.getCartId());
        if (cart == null) {
            throw new RuntimeException("购物车项不存在");
        }
        
        // 验证购物车项是否属于当前用户
        if (!userOpenid.equals(cart.getUserId())) {
            throw new RuntimeException("无权限操作此购物车项");
        }
        
        GoodsSpec spec = goodsSpecService.getById(cart.getSpecId());
        if (spec == null) {
            throw new RuntimeException("商品规格不存在");
        }
        if (spec.getStockNum() == null || spec.getStockNum() < dto.getQuantity()) {
            throw new RuntimeException("规格库存不足");
        }
        
        cart.setQuantity(dto.getQuantity());
        this.updateById(cart);
    }
}